package com.test.BTClient;



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.test.BTClient.DeviceListActivity;
import com.test.BTClient.Utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class BTClient extends Activity implements AdapterView.OnItemSelectedListener{
	private final static String TAG = "BTClient";
	private final static int REQUEST_CONNECT_DEVICE = 1;
	private final static int LOG_STATUS_SEND = 1;
	private final static int LOG_STATUS_REV = 2;
	
	private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";

	final String cmd_name_arr[]=new String[]{
			"身份证-获取模块编号",
			"身份证-获取模块状态",
			"身份证-寻找身份证",
			"身份证-选取身份证",
			"身份证-读文字照片信息",
			"指纹-连接设备",
			"指纹-获取版本信息",
			"指纹-获取设备参数",
			"指纹-初始化传感器",
			"指纹-采集上传图像",
			"指纹-采集特征",
			"指纹-上传特征1",
			"指纹-上传特征2",
			"指纹-指纹比对",
			"获取MCU软件版本号",
			"获取蓝牙软件版本号",
			"新指纹-测试通讯",
			"新指纹-采集指纹特征",
			"新指纹-探测手指",
			"新指纹-捕获指纹图像",
			"新指纹-上传指纹图像",
			"新指纹-生成指纹特征",
			"新指纹-把指纹特征上传",
			"新指纹-返回固件版本",
			"新指纹-获取寄存器数据",
	};
	final String cmd_str_arr[]=new String[]{
			"AA AA AA 96 69 00 03 12 FF EE",
			"AA AA AA 96 69 00 03 11 FF ED",
			"AA AA AA 96 69 00 03 20 01 22",
			"AA AA AA 96 69 00 03 20 02 21",
			"AA AA AA 96 69 00 03 30 01 32",
			"5B 00 04 01 00 00 00 05 5D",
			"5B 00 04 01 00 00 00 05 5D",
			"5B 00 04 01 00 00 01 04 5D",
			"5B 00 03 73 00 00 70 5D",
			"5B 00 07 44 00 00 0F 00 00 00 4C 5D",
			"5B 00 06 12 00 00 0A 00 00 1E 5D",
			"5B 00 03 13 00 00 10 5D",
			"5B 00 03 13 00 00 10 5D",
			"5B 00 03 30 00 00 33 5D",
			"4D 43 55 56 45 52 53 49 4F 4E 3F",
			"42 54 56 45 52 53 49 4F 4E 3F",
			"55 AA 01 00 00 00 00 00 80 00 80 01",
			"55 AA 01 00 00 00 00 00 81 00 81 01",
			"55 AA 01 00 00 00 00 00 82 00 82 01",
			"55 AA 01 00 00 00 00 00 83 00 83 01",
			"55 AA 01 00 00 00 00 00 84 00 84 01",
			"55 AA 01 00 00 00 00 00 85 00 85 01",
			"55 AA 01 00 00 00 00 00 86 00 86 01",
			"55 AA 01 00 00 00 00 00 87 00 87 01",
			"55 AA 01 00 00 00 00 00 89 00 89 01",
	};

	private InputStream is;
	//private TextView text0;
	private ListView logList;
	private LogAdapter logAdapter;
	private Spinner cmd_spinner;
    private EditText cmdEdit;
    //private TextView dis;
    //private ScrollView sv;
	private TextView byte_count_tv;
	private List<LogDetails> logData;
    private String smsg = "";
	private long smsgByteCount = 0;
    private String fmsg = "";
	private Context context;
    
    

    public String filename="";
    BluetoothDevice _device = null;
    BluetoothSocket _socket = null;
    boolean _discoveryFinished = false;    
    boolean bRun = true;
    boolean bThread = false;
	boolean isInputStreamClose = true;
	boolean isDestory = false;
	private long byts_count =0;
	
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
	
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		/*Calendar now = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date finishDate =formatter.parse("2017-06-15");
			Date nowDate = formatter.parse(formatter.format(new Date()));
			if( nowDate.compareTo(finishDate) == 1)
			{
				this.finish();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}*/

		setContentView(R.layout.main);
		context = this;
        //text0 = (TextView)findViewById(R.id.Text0);
		cmd_spinner = (Spinner)this.findViewById(R.id.cmd_spinner);
		SpinnerAdapter arrayAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, cmd_name_arr);
		cmd_spinner.setAdapter(arrayAdapter);
		cmd_spinner.setOnItemSelectedListener(this);

		byte_count_tv = (TextView)findViewById(R.id.byte_count_tv);
		cmdEdit = (EditText)findViewById(R.id.EditCMD);
		cmdEdit.addTextChangedListener(new Utils.CustomTextWatcher(cmdEdit));
        //sv = (ScrollView)findViewById(R.id.ScrollView01);
        //dis = (TextView) findViewById(R.id.in);
		byts_count = 0;
		byte_count_tv.setText(Long.toString(byts_count));

		logData = new ArrayList<LogDetails>();
		logData.clear();
		logAdapter = new LogAdapter();
		logList = (ListView)findViewById(R.id.ListLog);
		logList.setAdapter(logAdapter);

        if (_bluetooth == null){
        	Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

       new Thread(){
    	   public void run(){
    		   if(_bluetooth.isEnabled()==false){
        		_bluetooth.enable();
    		   }
    	   }   	   
       }.start();      
    }
    public void onSendButtonClicked(View v){
		if(bThread == false || bRun == false){
			Toast.makeText(this, "请连接蓝牙！", Toast.LENGTH_LONG).show();
			return;
		}
    	try{
    		OutputStream os = _socket.getOutputStream();
			byte[] buff = Utils.hexStr2Bytes(cmdEdit.getText().toString().replaceAll(" ", ""));
			if(buff.length == 0)
			{
				return;
			}
			LogDetails logDetails = new LogDetails(LOG_STATUS_SEND,cmdEdit.getText().toString(),buff.length);
			logData.add(logDetails);
			logAdapter.notifyDataSetChanged();
    		os.write(buff);
    	}catch(IOException e){  		
    	}  	
    }
	public void onSendCmdButtonClicked(View v)
	{
		if(bThread == false || bRun == false){
			Toast.makeText(this, "请连接蓝牙！", Toast.LENGTH_LONG).show();
			return;
		}
		try{
			OutputStream os = _socket.getOutputStream();
			byte[] buffCmd = Utils.hexStr2Bytes(cmd_str_arr[cmd_spinner.getSelectedItemPosition()].toString().replaceAll(" ", ""));
			LogDetails logDetails = new LogDetails(LOG_STATUS_SEND,cmd_str_arr[cmd_spinner.getSelectedItemPosition()].toString(),buffCmd.length);
			logData.add(logDetails);
			logAdapter.notifyDataSetChanged();
			os.write(buffCmd);
		}catch(IOException e){
		}
	}

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	switch(requestCode){
    	case REQUEST_CONNECT_DEVICE:
            if (resultCode == Activity.RESULT_OK) {
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                _device = _bluetooth.getRemoteDevice(address);

                try{
                	_socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
                }catch(IOException e){
                	Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                }
            	Button btn = (Button) findViewById(R.id.ButtonConnect);
                try{
                	_socket.connect();
                	Toast.makeText(this, "连接"+_device.getName()+"成功！", Toast.LENGTH_SHORT).show();
                	btn.setText("断开");
                }catch(IOException e){
                	try{
                		Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                		_socket.close();
                		_socket = null;
                	}catch(IOException ee){
                		Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                	}
                	
                	return;
                }

                try{
            		is = _socket.getInputStream();
					isInputStreamClose = false;
            		}catch(IOException e){
            			Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
            			return;
            		}
            		if(bThread==false){
            			ReadThread.start();
            			bThread=true;
            		}else{
            			bRun = true;
            		}
            }
    		break;
    	default:break;
    	}
    }
	boolean isSoftwareVersion(String str)
	{
		if((str.startsWith("MCU")||str.startsWith("BTVER")) && str.endsWith("END"))
			return true;
		return false;
	}
    Thread ReadThread=new Thread(){
    	
    	public void run(){
    		int num = 0;
    		byte[] buffer = new byte[1024];
    		int i = 0;
    		bRun = true;
    		while(!isDestory){
    			try{
    				while(isInputStreamClose && isDestory){
    					while(bRun == false && isDestory){}
    				}
    				while(!isDestory){
    					num = is.read(buffer);
						byts_count += num;
						byte[] bufferTmp = new byte[num];
						System.arraycopy(buffer, 0, bufferTmp, 0, num);
						String strTmp = new String(bufferTmp);
						String str = "";
						Log.d("wuguitong",strTmp);
						if(isSoftwareVersion(strTmp)) {
							str = strTmp;
						}else {
							str = Utils.byte2HexStr(bufferTmp);
						}
    					fmsg+=str + " ";
    					smsg+=str + " ";
						smsgByteCount += num;
    					if(is.available() == 0)break;
    				}
					handlerByteCount.sendMessage(handlerByteCount.obtainMessage());
					delayHander.removeCallbacks(delayRun);
					delayHander.postDelayed(delayRun,250);
    	    		}catch(IOException e){
    	    		}
    		}
    	}
    };
	Runnable delayRun = new Runnable() {
		@Override
		public void run() {
			handlerContent.sendMessage(handlerContent.obtainMessage());
		}
	};
	Handler delayHander = new Handler();
    Handler handlerContent= new Handler(){
    	public void handleMessage(Message msg){
    		super.handleMessage(msg);
			byte_count_tv.setText(Long.toString(byts_count));
			logData.add(new LogDetails(LOG_STATUS_REV, smsg,smsgByteCount));
			smsg = "";
			smsgByteCount = 0;
			logAdapter.notifyDataSetChanged();
    		//dis.setText(smsg);
    		//sv.scrollTo(0,dis.getMeasuredHeight());
    	}
    };
	Handler handlerByteCount= new Handler(){
		public void handleMessage(Message msg){
			super.handleMessage(msg);
			byte_count_tv.setText(Long.toString(byts_count));
		}
	};

    public void onDestroy(){
		if(_socket!=null) {
			try {
				isInputStreamClose = true;
				is.close();
				_socket.close();
			} catch (IOException e) {
			}
		}
		isDestory = true;
    	super.onDestroy();
    //	_bluetooth.disable();
    }
    

  /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }*/

  /*  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
        	if(_bluetooth.isEnabled()==false){
        		Toast.makeText(this, "Open BT......", Toast.LENGTH_LONG).show();
        		return true;
        	}
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.quit:
            finish();
            return true;
        case R.id.clear:
        	smsg="";
        	ls.setText(smsg);
        	return true;
        case R.id.save:
        	Save();
        	return true;
        }
        return false;
    }*/

    public void onConnectButtonClicked(View v){ 
    	if(_bluetooth.isEnabled()==false){
    		Toast.makeText(this, "请打开蓝牙！", Toast.LENGTH_LONG).show();
    		return;
    	}
    	

    	Button btn = (Button) findViewById(R.id.ButtonConnect);
    	if(_socket==null){
    		Intent serverIntent = new Intent(this, DeviceListActivity.class);
    		startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
    	}
    	else{
    	    try{
    	    	
    	    	is.close();
				isInputStreamClose = true;
    	    	_socket.close();
    	    	_socket = null;
    	    	bRun = false;
    	    	btn.setText("连接");
    	    }catch(IOException e){}   
    	}
    	return;
    }

    public void onSaveButtonClicked(View v){
    	Save();
    }

    public void onClearButtonClicked(View v){
    	//smsg="";
    	fmsg="";
		byts_count = 0;
    	//dis.setText(smsg);
		logData.clear();
		logAdapter.notifyDataSetChanged();
		byte_count_tv.setText(Long.toString(byts_count));
    	return;
    }

    public void onQuitButtonClicked(View v){
    	finish();
    }

	private void Save() {
		LayoutInflater factory = LayoutInflater.from(BTClient.this);
		final View DialogView =  factory.inflate(R.layout.sname, null);
		new AlertDialog.Builder(BTClient.this)
								.setTitle("文件名")
								.setView(DialogView)
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() //ȷ��������Ӧ����
										{
											public void onClick(DialogInterface dialog, int whichButton) {
												EditText text1 = (EditText) DialogView.findViewById(R.id.sname);
												filename = text1.getText().toString();

												try {
													if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

														filename = filename + ".txt";
														File sdCardDir = Environment.getExternalStorageDirectory();
														File BuildDir = new File(sdCardDir, "/data");
														if (BuildDir.exists() == false)
															BuildDir.mkdirs();
														File saveFile = new File(BuildDir, filename);
														FileOutputStream stream = new FileOutputStream(saveFile);
														stream.write(fmsg.getBytes());
														stream.close();
														Toast.makeText(BTClient.this, "存储成功！", Toast.LENGTH_SHORT).show();
													} else {
														Toast.makeText(BTClient.this, "没有存储卡！", Toast.LENGTH_LONG).show();
													}

												} catch (IOException e) {
													return;
												}


											}
										})
				.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) { 
									}
								}).show();
	}
	private class SpinnerAdapter extends ArrayAdapter<String> {
		Context context;
		String[] items = new String[] {};

		public SpinnerAdapter(final Context context,
							  final int textViewResourceId, final String[] objects) {
			super(context, textViewResourceId, objects);
			this.items = objects;
			this.context = context;
		}

		@Override
		public View getDropDownView(int position, View convertView,
									ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(context);
				convertView = inflater.inflate(
						android.R.layout.simple_spinner_item, parent, false);
			}

			TextView tv = (TextView) convertView
					.findViewById(android.R.id.text1);
			tv.setText(items[position]);
			tv.setTextSize(20);
			tv.setPadding(0, 10, 0, 10);
			return convertView;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(context);
				convertView = inflater.inflate(
						android.R.layout.simple_spinner_item, parent, false);
			}

			// android.R.id.text1 is default text view in resource of the android.
			// android.R.layout.simple_spinner_item is default layout in resources of android.

			TextView tv = (TextView) convertView
					.findViewById(android.R.id.text1);
			tv.setText(items[position]);
			tv.setTextSize(20);
			tv.setPadding(0,10,0,10);
			return convertView;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	public class LogAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return logData.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			if(convertView == null)
			{
				view=LayoutInflater.from(context).inflate(R.layout.log_item, null);
			}else{
				view = convertView;
			}
			TextView tv = (TextView)view.findViewById(R.id.log_item_text);
			TextView count_tv = (TextView)view.findViewById(R.id.log_count_item_text);
			LinearLayout linearLayoutContext = (LinearLayout)view.findViewById(R.id.log_item_context_layout);
			LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.log_item_layout);
			tv.setText(logData.get(position).getContecnt());
			count_tv.setText("字节数：" + logData.get(position).getBytesCount());
			if(logData.get(position).getStatus() == LOG_STATUS_REV){
				linearLayoutContext.setBackgroundResource(R.drawable.orange);
				linearLayout.setGravity(Gravity.LEFT);
			}else{
				linearLayoutContext.setBackgroundResource(R.drawable.greed);
				linearLayout.setGravity(Gravity.RIGHT);
			}

			return view;
		}
	}
	public class LogDetails {
		private int status;
		private String contecnt;
		private long bytesCount;

		LogDetails(int status,String contecnt,long bytesCount)
		{
			this.status = status;
			this.contecnt = contecnt;
			this.bytesCount = bytesCount;
		}
		public long getBytesCount() {
			return bytesCount;
		}

		public void setBytesCount(long bytesCount) {
			this.bytesCount = bytesCount;
		}

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}

		public String getContecnt() {
			return contecnt;
		}

		public void setContecnt(String contecnt) {
			this.contecnt = contecnt;
		}
	}
}